import * as types from './mutations-types'
import api from '../API'





export const getUserId = async function ({
  commit,
  state
}) {
  return await new Promise((resolve, reject) => {
    console.log('state.hasLogin', state.hasLogin);
    if (state.hasLogin) {
      resolve(state.userInfo)
    } else {
      uni.login({
        success: (res) => {
          console.log('wxlogin', res);
          if (res.errMsg === "login:ok") {
            commit('LOGIN')
            // 获取openid/
            api.getOpenid(res.code).then(userLoginInfo => {
              console.log('getOpenid', userLoginInfo);
              // userLoginInfo.userId = userLoginInfo.user_id
              console.log('userLoginInfo', userLoginInfo);
              // 有详细信息,存缓存

              if (userLoginInfo.avatarUrl) {
                commit('SETDATAILUSERINFO', userLoginInfo)
              } else {
                //userId/openid
                commit('SETUSERINFO', userLoginInfo)
              }
              resolve(userLoginInfo)
            })
          } else {
            // todo code fail.
            console.log('res.fail', res);
            reject(err)
          }
        },
        fail: (err) => {
          console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
          reject(err)
        }
      })
    }
  })
}

export const setUserInfoAction = function ({
  commit, state
}, userInfo) {
  return new Promise((resolve, reject) => {
    commit('SETDATAILUSERINFO', userInfo)
    // 获取详细信息存后台
    api.sendUserInfo(state.userInfo).then(saveRes => {
      console.log(saveRes);
    })
  })
}

export const getPhoneNumber = function ({
  commit, state
}, phoneObj) {
  return new Promise((resolve, reject) => {
    uni.login({
      success: (res) => {
        console.log('wxlogin', res);
        if (res.errMsg === "login:ok") {
          // 更新encryptedData
          api.updateSession({ code: res.code, unionId: state.userInfo.unionId }).then(userDatilInof => {
            console.log('userDatilInof', userDatilInof);
            commit('SETDATAILUSERINFO', userDatilInof)
            api.getPhone(phoneObj).then(phone => {
              console.log('phone', phone);
              if (phone.phoneNumber) {
                let setPhone = {
                  mobile: phone.phoneNumber
                }
                commit('SETDATAILUSERINFO', setPhone)
                resolve('获取手机成功')
              }
            })
          })
        }
        else {
          // todo code fail.
          console.log('verr', err);
          reject(err)
        }
      }
    })
  })
}
